package pl.edu.pw.elka.tinyrepo.dataserver.server;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import pl.edu.pw.elka.tinyrepo.common.FileProperties;
import pl.edu.pw.elka.tinyrepo.common.FilePropertiesSerializer;
import pl.edu.pw.elka.tinyrepo.common.HTTPHeaderType;
import pl.edu.pw.elka.tinyrepo.common.RequestHandler;
import pl.edu.pw.elka.tinyrepo.common.Response;
import pl.edu.pw.elka.tinyrepo.common.StatusCode;
import pl.edu.pw.elka.tinyrepo.gate.server.GateFacade;

public class PROPFINDRequestHandler extends DataServerRequestHandler {
	static private FilePropertiesSerializer serializer = new FilePropertiesSerializer();
	private File requestedFile = null;
	
	public PROPFINDRequestHandler(File dataCatalog, GateFacade gate) {
		this.dataCatalog = dataCatalog;
		this.gate = gate;
	}
	
	@Override
	public RequestHandler copy() {
		return new PROPFINDRequestHandler(dataCatalog, gate);
	}

	@Override
	public void run() {
		OutputStream out = null;
		try {
			if (incomming == null || request == null || dataCatalog == null)
				throw new RuntimeException("DATA SRV: impl problem");

			out = incomming.getOutputStream();
			requestedFile = new File(dataCatalog, request.getPath());

			//Odczytywanie informacji o pliku
			FileProperties properties = new FileProperties(requestedFile);
			String xml = serializer.toXML(properties);
			Response r = new Response(StatusCode.OK);
			r.addHeader(HTTPHeaderType.CONTENT_LENGTH, Integer.toString(xml.length()));
			r.addHeader(HTTPHeaderType.CONTENT_TYPE, "application/xml; charset=\"utf-8\"");
			r.write(out);
			//Wysylanie informacji do sekcji data
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
			writer.write(xml);
			writer.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Response r = new Response(StatusCode.NOT_FOUND);
			r.write(out);
			
		} catch (NullPointerException e) {
			throw new RuntimeException("DATA SRV: impl problem, requestedFile == null");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
}
